﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Framework.Extensions;
using Microsoft.Practices.Unity;

namespace Framework.Unity.Extensions
{
    public static class UnityContainerExtensions
    {
        public static Resolution<T> InstanceOf<T>(this IUnityContainer container)
        {
            return new Resolution<T>(container);
        }
    }

    public class Resolution<T>
    {
        private readonly IUnityContainer _container;
        private readonly List<ResolverOverride> _resolverOverrides = new List<ResolverOverride>();

        public Resolution(IUnityContainer container)
        {
            _container = container;
        }
        public Resolution<T> WithProperty<TProperty>(Expression<Func<T, TProperty>> propertyExpr, TProperty value)
        {
            var propertyName = propertyExpr.ToPath();
            return this.WithProperty(propertyName, value);
        }
        public Resolution<T> WithProperty<TProperty>(string propertyName, TProperty value)
        {
            _resolverOverrides.Add(new PropertyOverride(propertyName, value));
            return this;
        }
        public T Resolve()
        {
            return _container.Resolve<T>(_resolverOverrides.ToArray());
        }
        public TRes ResolveAs<TRes>()
        {
            return _container.Resolve<TRes>(_resolverOverrides.ToArray()); 
        }
    }
}
